package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {

    private static List<String> urlList = new ArrayList<>();

    // 初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }
    /**
     *
     * @param exchange 封装请求的上下文 request response
     * @param chain 过滤器链,可以放行 请求
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1. 获取请求路径,判断路径是否属于白名单路径

        String path = request.getURI().getPath();
        for (String s : urlList) {
            if (path.contains(s)){
                //如果属于白名单路径直接放行请求
                return chain.filter(exchange);
            }
        }
        //2.获取请求头中的token值
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //2.1 如果没有token 终止请求 返回401状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        try {
            //3. 检验token是否有效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //  -1：有效，0：有效，1：过期，2：过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i>0){
                //3.1如果token无效,终止请求,返回401 状态
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //3.2如果token有效,获取token 中的userId 并且将userId 设置到请求头中 路由给其他微服务
            Integer id = claimsBody.get("id", Integer.class);
            log.info("token网关校验成功   id:{},    URL:{}", id, request.getURI().getPath());
            // 4.将令牌信息传递到对应的微服务
            request.mutate().header("userId",String.valueOf(id));
            //返回结果
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("token 校验失败 :{}",e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }



    }
}
